package com.mango.community.controller;

import com.mango.community.entity.DiscussPost;
import com.mango.community.entity.Page;
import com.mango.community.entity.User;
import com.mango.community.service.DiscussPostService;
import com.mango.community.service.LikeService;
import com.mango.community.service.UserService;
import com.mango.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/19 21:12
 */
@Controller
public class HomeController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    /** 首页
     * @param model
     * @return
     */
    @RequestMapping(path = "/index",method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page){
        //方法调用前，会自动实例化model 会将Page 自动注入给model
        //所以在thymeleaf 模板中可以直接使用page对象中的数据
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index");
        //根据排序查询出前十条数据
        List<DiscussPost> discussPost = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit());
        List<Map<String,Object>> discussPosts= new ArrayList<>();
        if(discussPost != null){
            for (DiscussPost post : discussPost) {
                Map<String,Object> map = new HashMap<>();
                map.put("post",post);
                map.put("user",userService.findUserById(post.getUserId()));
                //点赞数量的获取
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,post.getId());
                map.put("likeCount",likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "index";
    }


    /** 返回错误页面
     * @return
     */
    @GetMapping("/error")
    public String getErrorPage(){
        return "/error/500";
    }
}
